package com.yoyo.itravel.web.controller;

import com.yoyo.itravel.bean.ResultInfo;
import com.yoyo.itravel.bean.Sight;
import com.yoyo.itravel.bean.SightComment;
import com.yoyo.itravel.bean.User;
import com.yoyo.itravel.constants.UserConstant;
import com.yoyo.itravel.exceptions.SightCommentException;
import com.yoyo.itravel.exceptions.TicketTypeDetailException;
import com.yoyo.itravel.service.ISightCommentService;
import com.yoyo.itravel.service.ITicketTypeDetailService;
import com.yoyo.itravel.utils.JSONUtils;
import com.yoyo.itravel.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author HZX
 * @Description 景点评论服务端
 * @date 2020/5/21 20:48
 */
@Controller
@RequestMapping("/comment")
public class SightCommentController {

    @Autowired
    private ISightCommentService sightCommentService;
    @Autowired
    private ITicketTypeDetailService ticketTypeDetailService;

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @Description 提交评论
     */
    @RequestMapping("/submitComment")
    protected void submitComment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取数据
        String detailTypeId = request.getParameter("detailTypeId");
        String starNum = request.getParameter("startNum");
        String imgArr = request.getParameter("imgArr");
        String content = request.getParameter("comment");
        System.out.println(imgArr);
        ResultInfo info = new ResultInfo();

        // 获得当前登录用户
        User user = (User)request.getSession().getAttribute(UserConstant.USER);

        if (user == null) {
            return;
        }

        String savePathUrl = null; // 图片保存在项目中的路径
        String[] imgPaths = new String[5]; // 保存图片路径

        if (!StringUtils.isEmpty(imgArr)) {
            // 切割
            String[] imgBase64Strs = imgArr.split("&");

            for (int i = 0; i < imgBase64Strs.length; i++) {
                String imgBase64Str = imgBase64Strs[i];

                if (StringUtils.isEmpty(imgBase64Strs)) {
                    continue;
                }

                String imageUrl = null; // 图片保存在数据库中的路径

                // 设置上传图片的保存路径
                String savePath = request.getServletContext().getRealPath("images/comment");

                File file = new File(savePath);
                // 判断上传文件的保存目录是否存在
                if (!file.exists() && !file.isDirectory()) {
                    // 创建目录
                    file.mkdirs();
                }

                byte[] bytes = StringUtils.parseBase64ToBytes(imgBase64Str);

                /** 字节流转文件 **/
                OutputStream fos = null;
                try {
                    // 新文件名（唯一）
                    String newFileName = new Date().getTime() + "." + imgBase64Str.substring(imgBase64Str.indexOf("/") + 1, imgBase64Str.indexOf(";"));
                    // 设置保存在数据库中的路径
                    imageUrl = "images/comment" + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + newFileName;
                    // 使用日期划分文件夹，防止一个文件夹下面文件过多
                    savePath = formatFolderByDate(savePath);
                    savePathUrl = savePath + File.separator + newFileName;

                    fos = new FileOutputStream(new File(savePathUrl));

                    fos.write(bytes);
                    fos.flush();
                    fos.close();

                    // 添加评论图片路径到数组中
                    imgPaths[i] = imageUrl;

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        try {
            // 通过门票具体类型id查找对应的景点对象
            Sight sight = ticketTypeDetailService.findSight(detailTypeId);

            // 构建评论对象
            SightComment sightComment = new SightComment(content, Integer.parseInt(starNum), new Date(), sight.getSightId(), user.getUserId());
            // 添加评论到数据库（包括了插入评论图片到数据库）
            sightCommentService.addComment(sightComment, imgPaths);
            // 添加成功
            info.setFlag(true);
            JSONUtils.writeValueToResponse(info, response);
        } catch (SightCommentException e) {
            e.printStackTrace();
            info.setFlag(false);
            info.setErrorMsg(e.getMessage());
            JSONUtils.writeValueToResponse(info, response);
        } catch (TicketTypeDetailException e) {
            e.printStackTrace();
            info.setFlag(false);
            info.setErrorMsg(e.getMessage());
            JSONUtils.writeValueToResponse(info, response);
        }


    }

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @Description 通过景点id获得该景点的所有评论
     */
    @RequestMapping("/findAllBySightIdAndStar")
    protected void findAllBySightIdAndStar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sightId = request.getParameter("sightId");
        String starNum = request.getParameter("starNum");

        Integer star = null;
        if (!"null".equals(starNum) && starNum != null && !"".equals(starNum)) {
            star = Integer.parseInt(starNum);
        }

        try {
            List<SightComment> comments = sightCommentService.findAllBySightIdAndStar(sightId, star);
            System.out.println(comments);
            JSONUtils.writeValueToResponse(comments, response);
        } catch (SightCommentException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @Description 点赞
     */
    @RequestMapping("/updateLikeNum")
    protected void updateLikeNum(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String commentId = request.getParameter("commentId");
        String isAdd = request.getParameter("isAdd");
        ResultInfo info = new ResultInfo();

        try {
            sightCommentService.updateLikeNum(commentId, Boolean.parseBoolean(isAdd));
            info.setFlag(true);
            JSONUtils.writeValueToResponse(info, response);
        } catch (SightCommentException e) {
            e.printStackTrace();
            info.setFlag(false);
            info.setErrorMsg(e.getMessage());
            JSONUtils.writeValueToResponse(info, response);
        }
    }

    /**
     * @param upload_folder_path
     * @return java.lang.String
     * @Description 使用当前日期作为上传文件的二级目录
     */
    private String formatFolderByDate(String upload_folder_path) {
        // 得到当前日期的年月日
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        // 构建一个File对象--在upload_folder_path下建立一个名称为date的文件夹
        File file = new File(upload_folder_path, date);
        // 判断是否存在
        if (!file.exists()) {
            file.mkdir();
        }

        // 返回该文件所指向的路径
        return file.toString();
    }
}
